package main

import (
	"fmt"
	"gin_maker_chat/dao"
	"gin_maker_chat/redis"
	"net"
	"time"
)

// 处理和客户端的通信
func Handler(conn net.Conn) {
	defer conn.Close()
	//接收客户端发送的消息
	process := &Processor{
		Conn: conn,
	}

	err := process.process()
	if err != nil {
		fmt.Println("客户端和服务端协程通信异常，err=", err)
		return
	}
}

// 启动服务器的接口
func StartServer() {

	sip := "127.0.0.1"
	port := 8888
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", sip, port))

	if err != nil {
		fmt.Println("net.Listen err:", err)
		return
	}
	defer listener.Close()

	//启动监听器的goroutine
	// go this.ListenMessage()

	//accept
	for {
		fmt.Println("等待客户端链接服务器")
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listener accept err:", err)
			continue
		}

		// do handler  处理和客户端的通信
		go Handler(conn)

	}

}

// 完成对UserDao的初始化任务
func initUserDao() {
	dao.MyUserDao = dao.NewUserDao(redis.Pool)
}

func main() {
	fmt.Println("初始化redis连接池.....")
	redis.InitPool("127.0.0.1:6379", "1234567890", 16, 0, 500*time.Second)
	initUserDao()
	fmt.Println("New Struct coding.....")
	StartServer()
}
